<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="130px">
      <el-form-item label="小区名称" prop="warnCheck">
        <el-cascader v-model="deptId" :options="deptTree" :props="propsDept" :show-all-levels="false" @change="handleQuery" clearable></el-cascader>
      </el-form-item>
      <el-form-item label="报警类别" prop="warnType">
        <el-select v-model="queryParams.warnType" placeholder="请选择" @change="handleQuery">
          <el-option label="电动车" value="电动车" />
          <el-option label="锂电池" value="锂电池" />
        </el-select>
      </el-form-item>
      <el-form-item label="报警地址" prop="warnAddress">
        <el-input v-model="queryParams.warnAddress" placeholder="请输入报警信息" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="报警信息是否查看" prop="warnCheck">
        <el-select v-model="queryParams.warnCheck" placeholder="请选择" @change="handleQuery">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select> -->
      <!-- <el-input
            v-model="queryParams.warnCheck"
            placeholder="请输入报警信息是否查看"
            clearable
            @keyup.enter.native="handleQuery"
          /> -->
      <!-- </el-form-item> -->
      <el-form-item label="报警信息是否处理" prop="warnHandle">
        <el-select v-model="queryParams.warnHandle" placeholder="请选择" @change="handleQuery">
          <el-option v-for="item in dispose" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
        <!-- <el-input
            v-model="queryParams.warnHandle"
            placeholder="请输入报警信息是否处理"
            clearable
            @keyup.enter.native="handleQuery"
          /> -->
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['camera:warn:add']"
          >新增</el-button>
        </el-col> -->
      <!-- <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['camera:warn:edit']"
          >修改</el-button>
        </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['camera:warn:remove']"
          >删除</el-button
        >
      </el-col> -->
      <el-col :span="1.5">
        <!-- <el-button type="danger" plain icon="el-icon-thumb" size="mini" :disabled="multiple" @click="batchProcessing">批量处理</el-button> -->
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['camera:warn:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="warnList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="小区楼栋信息" align="center">
        <template slot-scope="{ row }">
          <div>
            {{ findAncestors(deptTree, row.deptId).join("-") }}
          </div>
        </template>
      </el-table-column> -->
      <el-table-column align="center" label="报警类别" prop="warnType" width="80px">
        <!-- <template v-slot="{ row }">
          <img style="width: 30px;" v-if="row.warnType === '电动车'" src="./电动车.png" alt="电动车">
          <img style="width: 30px;" v-else-if="row.warnType === '锂电池'" src="./锂电池.png" alt="锂电池">
        </template> -->

      </el-table-column>
      <el-table-column label="报警地址" align="center" prop="alarmAddress" />
      <el-table-column label="报警摄像头" align="center" prop="alarmCamera" />
      <!-- <el-table-column label="报警地址" align="center" prop="address" width="120" /> -->
      <el-table-column label="报警截图" align="center" prop="warnPicture" width="120">
        <template v-slot="{ row }">
          <div v-if="row.warnPicture" style="display: flex">
            <div v-for="(v, i) in row.warnPicture.split(',')" :key="i">
              <el-image :src="baseUrl + v" :preview-src-list="row.warnPicture.split(',').map((v1) => baseUrl + v1)"></el-image>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="识别相似度" align="center" prop="warnSimilarity" />
      <!-- <el-table-column label="报警信息是否查看" align="center" prop="warnCheck">
        <template v-slot="{ row }">
          <el-tag :type="row.warnCheck == 0 ? 'danger ' : 'success'">{{ row.warnCheck == 0 ? "未查看" : "已查看" }}</el-tag>
        </template>
      </el-table-column> -->
      <el-table-column label="报警信息是否处理" align="center" prop="warnHandle">
        <template v-slot="{ row }">
          <el-tag :type="row.warnHandle == 0 ? 'danger ' : 'success'">{{ row.warnHandle == 0 ? "未处理" : "已处理" }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="时间" align="center" prop="createTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!-- <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['camera:warn:edit']">修改</el-button> -->
          <el-button v-if="scope.row.warnHandle == '1'" size="mini" type="text" icon="el-icon-view" @click="examine(scope.row)">查看</el-button>
          <el-button v-else size="mini" type="text" icon="el-icon-thumb" @click="examine(scope.row)">处理</el-button>

        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改摄像头预警对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body :show-close="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20" class="header">
          <el-col :span="12">
            <el-form-item label="报警类型" prop="warnType">
              <el-input v-model="form.warnType" placeholder="请输入报警信息" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报警地址" prop="warnAddress">
              <el-input v-model="alarmAddress" placeholder="请输入报警信息" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报警设备" prop="warnAddress">
              <el-input v-model="alarmCamera" placeholder="请输入报警信息" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="识别相似度" prop="warnSimilarity">
              <el-input v-model="form.warnSimilarity" placeholder="请输入识别相似度" disabled />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="负责人" prop="leader">
              <el-input v-model="form.leader" placeholder="请输入负责人" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入负责人电话" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报警截图" prop="warnPicture">
              <el-image :src="`${baseUrl}${form.warnPicture}`" fit="cover" :preview-src-list="[`${baseUrl}${form.warnPicture}`]" style="width: 200px; height: 200px"></el-image>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报警是否处理" prop="warnHandle">
              <el-input v-model="form.warnHandle" placeholder="请输入报警信息是否处理" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.handlePicture != null">
            <el-form-item label="处理图片" prop="handlePicture">
              <el-image :src="`${baseUrl}${form.handlePicture}`" fit="cover" :preview-src-list="[`${baseUrl}${form.handlePicture}`]" style="width: 200px; height: 200px"></el-image>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="处理时间" prop="updateTime">
              <el-input v-model="form.updateTime" placeholder="请输入处理时间" disabled />
            </el-form-item>

          </el-col>

          <el-col :span="12">
            <el-form-item label="处理人电话" prop="phonenumber">
              <el-input v-model="form.phonenumber" placeholder="请输入处理人电话" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="处理人" prop="userName">
              <el-input v-model="form.userName" placeholder="请输入处理人" disabled />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="处理经过" prop="handleDescribe">
              <el-input type="textarea" v-model="form.handleDescribe" placeholder="请输入处理经过" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.handlePicture == null">
            <el-form-item label="上传图片" prop="handlePicture" label-width="110px">
              <el-upload :action="uploadImgUrl" list-type="picture-card" :show-file-list="true" :file-list="fileList" :limit="1" :multiple="true" :headers="headers" :on-error="handleUploadError"
                :on-success="handleUploadSuccess" :on-preview="handlePictureCardPreview">
                <i class="el-icon-plus"></i>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible" append-to-body>
                <img width="100%" :src="dialogImageUrl">
              </el-dialog>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <!-- <el-button type="primary" @click="submitForm">确 定</el-button> -->
        <el-button type="primary" @click="manage">确 定</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-dialog>
    <!-- 处理框 -->
    <el-dialog title="处理预警信息" :visible.sync="processBox" width="500px" append-to-body :close-on-click-modal="false" :show-close="false">
      <el-form ref="form" :model="form" :rules="rules">
        <el-form-item label="上传图片" prop="handlePicture" label-width="110px">
          <el-upload :action="uploadImgUrl" list-type="picture-card" :show-file-list="true" :file-list="fileList" :limit="1" :multiple="true" :headers="headers" :on-error="handleUploadError"
            :on-success="handleUploadSuccess" :on-preview="handlePictureCardPreview">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible" append-to-body>
            <img width="100%" :src="dialogImageUrl">
          </el-dialog>
        </el-form-item>

        <el-form-item label="处理经过" prop="handleDescribe">
          <el-input type="textarea" v-model="form.handleDescribe" placeholder="请输入处理经过" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="manage">确 定</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
  
  <script>
import {
  listWarn,
  getWarn,
  delWarn,
  addWarn,
  updateWarn,
  handleWarn,
  getWarnById,
  getWarnCount,
} from "@/api/camera/warn";
import { getToken } from "../../../utils/auth";
import { bus } from "@/main";
import {
  deptTreeSelect,
} from "@/api/system/user";

export default {
  name: "Warn",
  data () {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
      fileList: [],
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      //处理框
      processBox: false,
      dialogVisible: false,
      dialogImageUrl: "",
      //地址
      alarmAddress: "",
      //报警摄像头
      alarmCamera: "",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 摄像头预警表格数据
      warnList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        warnAddress: null,
        cameraId: null,
        warnCheck: null,
        warnSimilarity: null,
        warnHandle: "",
        del: null,
        warnType: ""
        // address: ""
      },
      warnAmount: 0,
      // 表单参数
      form: {
        warnHandle: "",
      },
      options: [
        {
          value: "0",
          label: "未查看",
        },
        {
          value: "1",
          label: "已查看",
        },
      ],
      dispose: [
        {
          value: "0",
          label: "未处理",
        },
        {
          value: "1",
          label: "已处理",
        },
      ],
      // 表单校验
      rules: {
        // address: [
        //   { required: true, message: "报警地址不能为空", trigger: "blur" },
        // ],
        warnAddress: [
          { required: true, message: "报警信息不能为空", trigger: "blur" },
        ],
        warnPicture: [
          { required: true, message: "报警截图不能为空", trigger: "blur" },
        ],
        handleDescribe: [
          { required: true, message: "处理经过不能为空", trigger: "blur" },
        ],
        // handlePicture: [
        //   { required: true, message: "处理图片不能为空", trigger: "blur" },
        // ],
        cameraId: [
          {
            required: true,
            message: "报警摄像头uuid不能为空",
            trigger: "blur",
          },
        ],
        warnCheck: [
          {
            required: true,
            message: "报警信息是否查看不能为空",
            trigger: "blur",
          },
        ],
        warnHandle: [
          {
            required: true,
            message: "报警信息是否处理不能为空",
            trigger: "blur",
          },
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" },
        ],
      },
      propsDept: {
        checkStrictly: true,
        expandTrigger: "hover",
        value: "id",
      },
      deptTree: [],
      deptId: null,
    };
  },
  created () {
    console.log(2222);
    this.getListDept();
    this.getAmount();

    this.$root.$on("data-changed", () => {
      this.getList(); // 数据发生变化时刷新列表
    });

  },
  mounted () {
    this.getList();
  },
  watch: {
    warnAmount: {
      handler: function (newVal, oldVal) {
        if (newVal !== null && newVal !== undefined) { // 添加条件判断
          if (newVal !== oldVal) {
            this.getList();
          }
        }
      },
      immediate: true
    }
  },
  methods: {
    //批量处理
    // batchProcessing(){

    // },
    // findAncestors (tree, id, ancestors = []) {
    //   if (!tree || !Array.isArray(tree)) {
    //     return []; // 如果tree为空或者不是数组，直接返回空数组
    //   }

    //   for (const node of tree) {
    //     if (node.id == id) {
    //       return ancestors.concat(node.label || ''); // 添加空值判断
    //     }
    //     if (node.children && node.children.length > 0) {
    //       const foundAncestors = this.findAncestors(
    //         node.children,
    //         id,
    //         ancestors.concat(node.label || '') // 添加空值判断
    //       );
    //       if (foundAncestors) {
    //         if (foundAncestors[0] == "所有小区") {
    //           foundAncestors.shift();
    //         }
    //         return foundAncestors;
    //       }
    //     }
    //   }
    //   return []; // 如果未找到匹配的节点，则返回空数组
    // },
    getListDept () {
      deptTreeSelect().then((res) => {
        this.deptTree = res.data;
        this.deptId = this.deptTree[0].id;
        // this.getList();
      });
    },
    /** 查询摄像头预警列表 */
    getList () {
      this.loading = true;
      // console.log(123456, this.deptId);
      this.queryParams.deptId = this.deptId ? this.deptId.toString().split(",").at(-1) : null;
      listWarn(this.queryParams).then((response) => {
        this.warnList = response.rows;
        this.total = response.total;
        //保留warnAddress空格前面的数据，赋值给alarmAddress
        this.warnList.forEach((v) => {
          v.alarmAddress = v.warnAddress.split(" ")[0];
          v.alarmCamera = v.warnAddress.split(" ")[1];
        });

        this.loading = false;
      });
    },
    getAmount () {
      getWarnCount().then((res) => {
        this.warnAmount = res.data; // 将获取到的数据赋值给warnAmount
        // console.log(this.warnAmount, 111111111111);
      });
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.processBox = false;
      this.reset();
      this.getList();
    },
    // 表单重置
    reset () {
      this.form = {
        id: null,
        warnAddress: null,
        warnPicture: null,
        handlePicture: null,
        handleDescribe: "",
        handlePicture: null,
        cameraId: null,
        warnCheck: null,
        warnHandle: "",
        createTime: null,
        updateTime: null,
        del: null,
      };
      this.fileList = []
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.deptId = this.deptTree[0].id;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.reset();
      this.open = true;
      this.title = "添加摄像头预警";
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.reset();
      const id = row.id || this.ids;
      getWarn(id).then((response) => {
        this.form = response.data;
        this.form.warnCheck == 0
          ? (this.form.warnCheck = "未查看")
          : (this.form.warnCheck = "已查看");
        this.form.warnHandle == 0
          ? (this.form.warnHandle = "未处理")
          : (this.form.warnHandle = "已处理");
        this.open = true;
        this.title = "修改摄像头预警";
      });
    },
    //处理按钮
    handleProcess (id) {
      this.reset();
      this.processBox = true;
      getWarnById(id).then((response) => {
        this.form = response.data;
        if (response.data.handlePicture) {
          this.fileList = response.data.handlePicture.split(",").map((v) => {
            return {
              name: v,
              url: this.baseUrl + v,
            };
          });
        }
      });
    },
    // 确认处理按钮
    manage () {
      this.form.warnHandle = 1;
      this.open = false;
      // 调用更新预警信息的接口
      updateWarn(this.form)
        .then(response => {
          this.processBox = false;
          // const currentTime = new Date();
          // this.form.updateTime = currentTime;
          this.$message.success("摄像头预警信息处理成功");
          // 刷新预警列表
          this.getList();
        })
        .catch(error => {
          console.error("摄像头预警信息修改失败", error);
          this.$message.error("摄像头预警信息修改失败，请重试");
        });
    },
    // 查看按钮
    examine (row) {
      const id = row.id || this.ids;
      getWarnById(id).then((response) => {
        this.form = response.data;
        this.alarmAddress = this.form.warnAddress.split(" ")[0];
        this.alarmCamera = this.form.warnAddress.split(" ")[1];
        // if (response.data.warnPicture) {
        //   this.fileList = response.data.warnPicture.split(",").map((v) => {
        //     return {
        //       name: v,
        //       url: this.baseUrl + v,
        //     };
        //   });
        // };
        if (response.data.handlePicture) {
          this.fileList = response.data.handlePicture.split(",").map((v) => {
            return {
              name: v,
              url: this.baseUrl + v,
            };
          });
        }
        this.form.warnHandle == 0
          ? (this.form.warnHandle = "未处理")
          : (this.form.warnHandle = "已处理");
        this.open = true;
        this.title = "查看摄像头预警";
      });
    },
    /** 提交按钮 */
    submitForm () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateWarn(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addWarn(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除摄像头预警编号为"' + ids + '"的数据项？')
        .then(function () {
          return delWarn(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport () {
      this.download(
        "camera/warn/export",
        {
          ...this.queryParams,
        },
        `warn_${new Date().getTime()}.xlsx`
      );
    },
    // 删除图片
    handleRemove (file, fileList) {
      this.form.handlePicture = fileList.map(f => f.url).join(',');
    },
    // 显示图片
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 上传失败
    handleUploadError () {
      this.$message("图片上传失败，请重试");
    },
    // 上传成功
    handleUploadSuccess (response, file, fileList) {
      this.form.handlePicture = fileList.map(f => {
        if (f.response) {
          return f.response.fileName
        }
        return f.url
      }).join(',');
    },
    updateHandleStatus (value) {
      this.form.warnHandle = value === '已处理' ? 1 : 0;
    }

  },
};

</script>
  